package cn.fl.ass.service.impl;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssDealRedeemService;
import cn.fl.ass.transform.AssDealRedeemVOTransform;
import cn.fl.ass.vo.AssDealRedeemVO;
import cn.fl.capital.condition.CapOverdueInfoQueryCondition;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.constant.CapPayInfoConstant;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapOverdueInfoService;
import cn.fl.capital.service.ICapPayInfoService;
import cn.fl.capital.vo.CapOverdueInfoVO;
import cn.fl.capital.vo.CapPayInfoVO;
import cn.fl.commons.result.ResponseData;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.IPrjPrdDtlGpsApiService;
import cn.fl.preloan.dto.gps.GpsDeviceDTO;
import cn.fl.project.condition.PrjPaySchMYqQC;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.condition.PrjPrdDtlSchRQC;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.project.dto.PrjPrdDtlSchRDTO;
import cn.fl.project.service.IPrjPaySchMYqService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.project.vo.PrjPaySchMYqVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.ass.facade.api.IAssDealRedeemApi;
import fl.ass.facade.condition.AssDealRedeemQueryCondition;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.AssDealRedeemDTO;
import fl.ass.facade.dto.MessageDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

/**
 * @Description: 处置赎回表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssDealRedeemServiceImpl implements IAssDealRedeemService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IAssDealRedeemService.class);

	@Autowired
	private IAssDealRedeemApi assDealRedeemApi;

    @Autowired
    private IPrjPrdDtlService prjPrdDtlService;

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

    @Autowired
    private IPrjPaySchMYqService prjPaySchMYqService;

    @Autowired
    private ICapPayInfoService capPayInfoService;

    @Autowired
    private ICapOverdueInfoService capOverdueInfoService;

    @Autowired
    private IPrjPrdDtlGpsApiService prjPrdDtlGpsApiService;

    @Autowired
    private ISysUsrApiService sysUsrApiService;

	@Override
	public AssDealRedeemVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			return null;
		}
		//查询赎回主表信息
		MessageDTO<AssDealRedeemDTO> response = this.assDealRedeemApi.findAssDealRedeemById(id);
		return AssDealRedeemVOTransform.toVO(response.getData());
	}

	@Override
	public Long add(AssDealRedeemVO entity) throws BaseException{
		if(null == entity){
			return null;
		}
		MessageDTO<String> response = this.assDealRedeemApi.saveAssDealRedeem(AssDealRedeemVOTransform.toDTO(entity));
		return response.getId();
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			return false;
		}
		//return this.assDealRedeemApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(AssDealRedeemVO entity) throws BaseException{
		if(null == entity){
			return false;
		}
		//返回逻辑值-JL-20170409
		MessageDTO<String> response = this.assDealRedeemApi.updateAssDealRedeem(AssDealRedeemVOTransform.toDTO(entity));
		return response.isSuccess();
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		//return this.assDealRedeemApiService.searchListPage(page);
		//TODO 业务逻辑
		return null;
	}

	@Override
	public List<AssDealRedeemVO> searchAssDealRedeemList(
			AssDealRedeemQueryCondition condition) throws BaseException {
		MessageDTO<AssDealRedeemDTO> dtoList = this.assDealRedeemApi.searchList(condition);
		List<AssDealRedeemVO> voList = new ArrayList<AssDealRedeemVO>();
		if(null != dtoList.getDatas()){
			for (AssDealRedeemDTO dto : dtoList.getDatas()) {
				voList.add(AssDealRedeemVOTransform.toVO(dto));
			}
		}
		return voList;
    }

    @Override
    public Map<String, Double> getCalcStlCstIRRAndDiscount(Long paySchId, Long stlAmt, Date stlStDt) throws BaseException {
        return this.assDealRedeemApi.getCalcStlCstIRRAndDiscount(paySchId, stlAmt, stlStDt);
    }

    @Override
    public boolean saveStlCstIrrAndDiscountAmt(Long redeemId, Long paySchId, Double stlCstIrr, Double discountAmt, Long usrId) throws BaseException {
        return this.assDealRedeemApi.saveStlCstIrrAndDiscountAmt(redeemId, paySchId, stlCstIrr, discountAmt, usrId);
    }

    @Override
    public DataResultVO checkAssRedeemFlow4YQ(String redeemTypCd, Long prjPrdDtlId) throws BaseException {
        try {
            DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "");
            // 校验是否有YQ业务且已结清
            PrjPrdDtlSchRQC prjPrdDtlSchRQC = new PrjPrdDtlSchRQC();
            prjPrdDtlSchRQC.setPrjPrdDtlId(Long.valueOf(prjPrdDtlId));
            List<PrjPrdDtlSchRDTO> prjPrdDtlSchRDTOS = this.prjPrdPaySchMApiService.searchDtlSchRList(prjPrdDtlSchRQC);
            List<Long> paySchIds = new ArrayList<>(prjPrdDtlSchRDTOS.size());
            for (PrjPrdDtlSchRDTO prjPrdDtlSchRDTO : prjPrdDtlSchRDTOS) {
                paySchIds.add(prjPrdDtlSchRDTO.getPaySchId());
            }
            PrjPaySchMYqQC prjPaySchMYqQC = new PrjPaySchMYqQC();
            prjPaySchMYqQC.setPaySchIds(paySchIds);
            List<PrjPaySchMYqVO> prjPaySchMYqVOS = this.prjPaySchMYqService.searchList(prjPaySchMYqQC);
            if (CollectionUtils.isNotEmpty(prjPaySchMYqVOS)) {
                // 疫情支付表集合
                List<Long> yqPaySchIds = new ArrayList<>(prjPaySchMYqVOS.size());
                for (PrjPaySchMYqVO prjPaySchMYqVO : prjPaySchMYqVOS) {
                    if (StringUtils.isEmpty(prjPaySchMYqVO.getYqPaySchId())) {
                        resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                        resultVO.setInfo("绑定未申请放款的车抵贷业务YQ项目，请先作废或放款");
                        return resultVO;
                    }
                    yqPaySchIds.add(prjPaySchMYqVO.getYqPaySchId());
                }

                // 校验是否有未放款支付表
                List<String> payStsCdList = new ArrayList<>(2);
                payStsCdList.add(CapPayInfoConstant.CODE_PAY_STS_CD_N_START);
                CapPayInfoQueryCondition capPayInfoQueryCondition = new CapPayInfoQueryCondition();
                capPayInfoQueryCondition.setPaySchIdList(yqPaySchIds);
                capPayInfoQueryCondition.setPayStsCdList(payStsCdList);
                capPayInfoQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
                capPayInfoQueryCondition.setIsValid(BaseConstant.IS_YESNO_YES);
                // 放款信息（未申请）
                List<CapPayInfoVO> capPayInfoVOS = this.capPayInfoService.searchList(capPayInfoQueryCondition);
                if (CollectionUtils.isNotEmpty(capPayInfoVOS)) {
                    resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    resultVO.setInfo("绑定未申请放款的车抵贷业务YQ项目，请先作废或放款");
                    return resultVO;
                }
                if (InterfaceConstants.REDEEM_TYPE_CD_1.equals(redeemTypCd)) {
                    // 校验是否有已放款但未结清的YQ支付表
                    PrjPrdDtlQueryCondition qc = new PrjPrdDtlQueryCondition();
                    qc.setPaySchIdList(yqPaySchIds);
                    qc.setIsDel(BaseConstant.IS_YESNO_NO);
                    List<PrjPrdDtlVO> prjPrdDtlVOS = prjPrdDtlService.selectList(qc);
                    if (CollectionUtils.isNotEmpty(prjPrdDtlVOS)) {
                        for (PrjPrdDtlVO prjPrdDtlVO : prjPrdDtlVOS) {
                            // 非已正常结清、非已提前结清、非已强制结清
                            if (!PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_03.equals(prjPrdDtlVO.getPrdStsCd()) &&
                                    !PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_05.equals(prjPrdDtlVO.getPrdStsCd()) &&
                                    !PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_40.equals(prjPrdDtlVO.getPrdStsCd())) {
                                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                                resultVO.setInfo("结清绑定车抵贷YQ业务后，可申请赎回。关联支付表号为：" + prjPrdDtlVO.getPaySchNo());
                                return resultVO;
                            }
                        }
                    }
                } else if (InterfaceConstants.REDEEM_TYPE_CD_2.equals(redeemTypCd)) {
                    CapOverdueInfoQueryCondition capOverdueInfoQueryCondition = new CapOverdueInfoQueryCondition();
                    capOverdueInfoQueryCondition.setPaySchIdList(yqPaySchIds);
                    capOverdueInfoQueryCondition.setDataStatusCd(CapitalConstant.CODE_OVD_DATA_CD_0);
                    List<CapOverdueInfoVO> capOverdueInfoVOS = capOverdueInfoService.searchList(capOverdueInfoQueryCondition);
                    if (CollectionUtils.isNotEmpty(capOverdueInfoVOS)) {
                        StringBuffer sb = new StringBuffer();
                        capOverdueInfoVOS.stream().forEach(capOverdueInfoVO -> {
                            if (StringUtils.isNotEmpty(capOverdueInfoVO.getOverdueAmount()) && !capOverdueInfoVO.getOverdueAmount().equals(0L)) {
                                sb.append("[" + capOverdueInfoVO.getPaySchNo() + "]");
                            }
                        });
                        if (0 != sb.length()) {
                            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                            resultVO.setInfo("绑定疫情贷支付表存在逾期，请消除逾期后申请赎回转正常。绑定疫情贷支付表为：" + sb.toString());
                            return resultVO;
                        }
                    }
                }

            }
            return resultVO;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("校验拖车赎回流程发起失败").setKeys("prjPrdDtlId:" + prjPrdDtlId, "redeemTypCd:" + redeemTypCd).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("校验拖车赎回流程发起失败").setKeys("prjPrdDtlId:" + prjPrdDtlId, "redeemTypCd:" + redeemTypCd).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    @Override
    public ResponseData validateGpsDeviceOfHadoop(String gpsDeviceNo, String customManagerWorkNum) throws BaseException {
        return prjPrdDtlGpsApiService.validateGpsDeviceOfHadoop(gpsDeviceNo, customManagerWorkNum);
    }

    @Override
    public ResponseData validateGPSIsUsed(String gpsCardNo, Long prjPrdDtlId) throws BaseException {
        return prjPrdDtlGpsApiService.isUsed(gpsCardNo, prjPrdDtlId);
    }

    @Override
    public DataResultVO validateGPS(List<String> gpsNos, Long prjPrdDtlId, Long cstMgrId) throws BaseException {
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_NO, "");
        if (CollectionUtils.isEmpty(gpsNos)) {
            return null;
        }
        if (StringUtils.isEmpty(prjPrdDtlId)) {
            throw new BaseException("项目产品明细id不能为空");
        }
        if (StringUtils.isEmpty(cstMgrId)) {
            throw new BaseException("客户经理id不能为空");
        }
        SysUsrDTO sysUsrDTO = sysUsrApiService.selectSysUsrById(Long.valueOf(cstMgrId), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
        Assert.notNull(sysUsrDTO, "未查到客户经理信息");
        // 实际姓名
        String refRlNm = sysUsrDTO.getRefRlNm();
        // 工号
        String usrNm = sysUsrDTO.getUsrNm();
        StringBuffer sb = new StringBuffer();
        Map<String, GpsDeviceDTO> map = new HashMap(3);
        for (String gpsNo : gpsNos) {
            BaseLogUtils.newLogger("查询GPS是否已占用参数：").setKeys("gpsNo:" + gpsNo, "prjPrdDtlId:" + prjPrdDtlId).info();
            ResponseData isUsed = validateGPSIsUsed(gpsNo, prjPrdDtlId);
            BaseLogUtils.newLogger("查询GPS是否已占用返回：").setKeys("isUsed:" + JSON.toJSONString(isUsed)).info();
            Assert.notNull(isUsed, "未获得校验本地GPS结果");
            if (BaseConstant.IS_YESNO_NO_STR.equals(String.valueOf(isUsed.getData()))) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("该GPS已被占用，" + "[" + gpsNo + "]");
                return resultVO;
            } else if ("2".equals(String.valueOf(isUsed.getData()))) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("GPS[" + gpsNo + "]数据错误，请核查");
                return resultVO;
            }
            BaseLogUtils.newLogger("查询大数据GPS是否已占用参数：").setKeys("gpsNo:" + gpsNo, "usrNm:" + usrNm).info();
            ResponseData response = validateGpsDeviceOfHadoop(gpsNo, usrNm);
            BaseLogUtils.newLogger("查询大数据GPS是否已占用返回：").setKeys("response:" + JSON.toJSONString(response)).info();
            Assert.notNull(response, "未获得校验大数据平台GPS结果");
            String code = response.getCode();
            if ("hy4013".equals(code)) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("未查询到GPS设备，请核查");
                return resultVO;
            } else if ("hy425".equals(code)) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("GPS平台未查到当前客户经理信息，请核查");
                return resultVO;
            } else if ("200".equals(code)) {
                GpsDeviceDTO gpsDeviceDTO = (GpsDeviceDTO) response.getData();
                String receiveName = gpsDeviceDTO.getReceiveName();
                if (StringUtils.isNotEmpty(receiveName) && !receiveName.equals(usrNm)) {
                    resultVO.setSuccess(2);
                    sb.append("【卡号：" + gpsNo + "的GPS设备领用人[" + gpsDeviceDTO.getReceiveRealName() + "]与实际使用人[" + refRlNm + "]不一致，是否继续安装？】");
                    map.put(gpsNo, gpsDeviceDTO);
                    continue;
                } else {
                    resultVO.setSuccess(BaseConstant.IS_YESNO_YES);
                    resultVO.setData(gpsDeviceDTO);
                }
            } else {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo(response.getMessage());
                return resultVO;
            }
        }
        if (2 == resultVO.getSuccess()) {
            resultVO.setInfo(sb.toString());
            resultVO.setData(map);
        }
        return resultVO;
    }

}

